<?php

	function calculateIncome($id, $retreaveInfo)
	{	
		$sql = "SELECT mu.id, mu.email, mu.url_name, mu.phone_no, mu.user_MGM_id, mu.fullname, mu.identity_no, mu.address1, mu.address2, mu.mobile_no, us.start_month, us.end_month,
				(SELECT 1 FROM mgm_users mu2 WHERE mu2.sponsor_id=mu.user_MGM_id LIMIT 1) AS child_status
				FROM mgm_users mu
				LEFT JOIN user_subscription us 
				ON mu.id = us.user_id
				WHERE mu.sponsor_id = '".$id."'
				AND (us.end_month = (SELECT MAX(us1.end_month) 
						   FROM user_subscription us1
						   WHERE us1.user_id = mu.id)
					OR us.end_month IS NULL)
				GROUP BY mu.id
				ORDER BY mu.id
				LIMIT 2";
		$result = mysql_query($sql);
		$numrowcheck = mysql_num_rows($result);
		$newTotalIncome = 0;
		$newActiveIncome = 0;
		while($row = mysql_fetch_array($result))
		{

			$statusActive = checkStatus($row['start_month'],$row['end_month']);
// 			echo $row['user_MGM_id']." --> ".$row['start_month']." --> ".$row['end_month']." --> ".$statusActive."<br/>";
			
			if($row['child_status'] == "1")
			{
				$html = $retreaveInfo->getTrees() . "<li><a href='index.php?page=tree&child=".$row['user_MGM_id']."' ".childNodeStyle($statusActive).">".$row['url_name']."</a><ul>";
				$retreaveInfo->setTrees($html);
				$childIncome = calculateIncome($row['user_MGM_id'], $retreaveInfo);
				$html = $childIncome->getTrees() . "</ul></li>";
			}
			else
			{
				$html = $retreaveInfo->getTrees() . "<li><a href='index.php?page=tree&child=".$row['user_MGM_id']."' ".childNodeStyle($statusActive).">".$row['url_name']."</a>";
				$retreaveInfo->setTrees($html);
				$childIncome = calculateIncome($row['user_MGM_id'], $retreaveInfo);
				$html = $childIncome->getTrees() . "</li>";
			}
			
			
			
			
			//	count total child
			$intTotalChild = intval($retreaveInfo->getTotalChild());
			$newTotalIncome =  $intTotalChild + 1;
// 			echo $row['user_MGM_id']." --> ".$newTotalIncome." --> ".$intTotalChild." --> ".$intTotalChild ."<br/>";
			
			//	count total active child
			if($statusActive == "myMonth")
			{
				$intTotalActive = intval($retreaveInfo->getTotalActive());
				$newActiveIncome =  $intTotalActive + 1;
			}
			
			$retreaveInfo->setTrees($html);
			$retreaveInfo->setTotalChild($newTotalIncome);
			$retreaveInfo->setTotalActive($newActiveIncome);
		}
		
		return $retreaveInfo;
	}
	
	function checkStatus($startDate, $endDate)
	{
		$today = time();
		$start = strtotime($startDate);
		$end = strtotime($endDate);
		$startMonth = gmdate("m Y", $start);
		$todayMonth = gmdate("m Y", $today);
		$endMonth = gmdate("m Y", $end);
		if ($todayMonth>=$startMonth && $todayMonth<=$endMonth)
		{
			$startMonth = gmdate("m", $start);
			$endMonth = gmdate("m", $end);
			$todayMonth = gmdate("m", $today);

			
			if($startMonth == $todayMonth)
			{
				return 'myMonth';
			}
			
			if($endMonth == $todayMonth)
			{
				return 'topup';
			}
			return 'active';
		}
		else
		{
			return 'expired';
		}
	}
	
	function parentBlockStyle($status)
	{
		if($status == "active" || $status == "myMonth" )
		{
			return "class='block-level emphasize-darkActive'";
		}
		else if($status == "topup")
		{
			return "class='block-level emphasize-darkTopup'";
		}
		else if($status == "expired")
		{
			return "class='block-level emphasize-darkExpired'";
		}
		else
		{
			return "";
		}
	}
	
	function childNodeStyle($status)
	{
		if($status == "active" || $status == "myMonth")
		{
			return "class='activeNode'";
		}
		else if($status == "topup")
		{
			return "class='topupNode'";
		}
		else if($status == "expired")
		{
			return "class='expiredNode'";
		}
		else
		{
			return "";
		}
	}
	
	function getChildTree($realParent)
	{
		$childSql = "SELECT mu.id, mu.email, mu.url_name, mu.phone_no, mu.user_MGM_id, mu.fullname, mu.identity_no, mu.address1, mu.address2, mu.mobile_no, us.start_month, us.end_month
		FROM mgm_users mu
		LEFT JOIN user_subscription us
		ON mu.id = us.user_id
		WHERE mu.sponsor_id = '$realParent'
		AND (us.end_month = (SELECT MAX(us1.end_month)
		FROM user_subscription us1
		WHERE us1.user_id = mu.id)
		OR us.end_month IS NULL )
		GROUP BY mu.id
		ORDER BY mu.id
		LIMIT 2";
		
		
		$childResult = mysql_query($childSql);
		
		$allInfo = new retreaveInfo(0, 0, " ");
		$allchild = array();
		$totalChild = 0;
		$listAllInfo = array();
		while($row = mysql_fetch_array($childResult))
		{
			$retreaveInfo = new retreaveInfo(0, 0, " ");
			$allInfo = calculateIncome($row['user_MGM_id'], $retreaveInfo, $con);
			$statusActive = checkStatus($row['start_month'],$row['end_month']);
			
			$my_date = date('m/d/y', strtotime($row['start_month']));
			$obj=new CustomerInfo($row['id'], $row['email'], $row['url_name'], $row['phone_no'], $row['user_MGM_id'], $row['fullname'], $row['identity_no'], $row['address1'], $row['address2'], $row['mobile_no'], $my_date, intval($allInfo->getTotalChild()), "", $statusActive);
			$allchild[] = $obj;
		
			if(trim($allInfo->getTrees()) == "" )
			{
				$dummy = "<li><a href='index.php?page=tree&child=".$row['user_MGM_id']."' ".childNodeStyle($statusActive).">".$row['url_name']."</a></li>";
				$totalChild = $totalChild + 1;
			}
			else {
				$dummy = "<li><a href='index.php?page=tree&child=".$row['user_MGM_id']."' ".childNodeStyle($statusActive).">".$row['url_name']."</a><ul>".$allInfo->getTrees()."</ul></li>";
				$totalChild = $totalChild + intval($allInfo->getTotalChild());
			}
			$allInfo->setTrees($dummy);
			$listAllInfo[] = $allInfo;
		}
		return $listAllInfo;
	}
	
	function getUserProfilebyMgmId($realParent)
	{

		$userSql = "SELECT mu.id, mu.email, mu.url_name, mu.phone_no, mu.user_MGM_id, mu.fullname, mu.identity_no, mu.address1, mu.address2, mu.mobile_no, us.start_month, us.end_month
		FROM mgm_users mu
		LEFT JOIN user_subscription us
		ON mu.id = us.user_id
		WHERE mu.user_MGM_id = '$realParent'
		AND (us.end_month = (SELECT MAX(us1.end_month)
		FROM user_subscription us1
		WHERE us1.user_id = mu.id)
		OR us.end_month IS NULL )";
		
		$userResult = mysql_query($userSql);
		
		$userProfileDB = mysql_fetch_array($userResult);
		$statusParent = checkStatus($userProfileDB['start_month'],$userProfileDB['end_month']);
		$my_date = date('m/d/y', strtotime($row['start_month']));
		$userProfile=new CustomerInfo($userProfileDB['id'], $userProfileDB['email'], $userProfileDB['url_name'], $userProfileDB['phone_no'], $userProfileDB['user_MGM_id'], $userProfileDB['fullname'], $userProfileDB['identity_no'], $userProfileDB['address1'], $userProfileDB['address2'], $userProfileDB['mobile_no'], $my_date, "", "", $statusParent);
		
		return $userProfile;
	}
	
	function getPreviousMonth()
	{
		$days_passed_this_month = date("j");
		$timestamp_last_month = time() - $days_passed_this_month *24*60*60;
		$last_month = date("F", $timestamp_last_month);
		return $last_month;
	}
	
	function calculateSingleEntryAndIncome($id, $mgm_id, $user_key_income_list)
	{
		foreach ($user_key_income_list as $child) 
		{
			if($count < 2)
			{
				// check if parent expire or not
				if($child->getStatus() != "expired")
				{
					if($child->getStatus() == "myMonth")
					{
						$parentEntry++;
					}
					
					// calculate available entry
					$childEntry = $childEntry + $child->getChildActive();
				}
			}
			else
			{
				$totalActive = 0;
				if($child->getStatus() != "expired")
				{
					// check if parent expire or not
					if($child->getStatus() == "myMonth")
					{
						$parentIncome++;
					}
					
					// calculate income based on total entry available
					$totalActive = $child->getChildActive();
					if($totalActive > $childEntry)
					{
						$totalActive = $totalActive - $childEntry;
					}
					$childIncome = $childIncome + $totalActive;
				}
				
			}
			$count++;
		}
		
		$totalCommission = ($parentEntry*6) + ($parentIncome*12) + ($childIncome*12);
		
		$incomeEntry=new EntryIncomeDeclaration($id, $mgm_id,  $parentEntry, $childEntry, $parentIncome, $childIncome, $totalCommission);
		
		return $incomeEntry;
	}

?>